package com.maimang.platform.crm.controller;

import cn.hutool.core.date.DateUtil;
import com.maimang.platform.annotation.Log;
import com.maimang.platform.base.BaseController;
import com.maimang.platform.base.Result;
import com.maimang.platform.common.entity.SysDeptTree;
import com.maimang.platform.common.service.SysUserDeptService;
import com.maimang.platform.common.utils.ExcelUtil;
import com.maimang.platform.crm.entity.CrmWorkRecord;
import com.maimang.platform.crm.entity.WorkTreeNode;
import com.maimang.platform.crm.service.WorkRecordService;
import com.maimang.platform.crm.util.TokenUtil;
import com.maimang.platform.enums.BusinessType;
import com.maimang.platform.lang.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Rocky
 * @version 1.0.0
 * @classname WorkRecordController
 * @description <br>工作记录信息操作处理</br>
 * @date 2019-09-23 15:42:23
 * @email jintaozhao@qq.com
 */
@Controller
@RequestMapping("/crm/workRecord")
@Api(value = "工作记录", description = "工作记录 信息操作处理接口")
public class WorkMobileController extends BaseController {

	@Autowired
	private WorkRecordService workRecordService;

	@Autowired
	private SysUserDeptService userDeptService;

	/**
	 * 查询工作记录列表
	 */
	@ApiOperation(value = "查询列表", notes = "查询工作记录列表信息")
	// @RequiresPermissions("crm:work:list")
	@PostMapping("/list")
	@ResponseBody
	public Result list(CrmWorkRecord workRecord) throws Exception {
		Result result = TokenUtil.verifyToken(workRecord.getKey());
		if (StringUtils.isNotNull(result))
			return result;
		startPage();
		List<CrmWorkRecord> list = workRecordService.selectWorkRecordList(workRecord);
		return Result.SUCCESS(getDataTable(list)) ;
	}

	/**
	 * 新增保存工作记录
	 */
	@ApiOperation(value = "新增保存", notes = "参数：CrmWorkRecord")
	// @RequiresPermissions("crm:work:add")
	@Log(title = "工作记录", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	public Result addSave(CrmWorkRecord workRecord) throws Exception {
		Result result = TokenUtil.verifyToken(workRecord.getKey());
		if (StringUtils.isNotNull(result))
			return result;
		return toResult(workRecordService.insertWorkRecord(workRecord));
	}

	@ApiOperation(value = "获取详情", notes = "参数：workId")
	// @RequiresPermissions("crm:work:edit")
	@Log(title = "工作记录", businessType = BusinessType.UPDATE)
	@GetMapping("/detail/{workId}")
	@ResponseBody
	public Result<CrmWorkRecord> getRecordById(@RequestParam(name = "key") String token, @PathVariable(value = "workId") Integer workId) {
		try {
			Result result = TokenUtil.verifyToken(token);
			if (StringUtils.isNotNull(result))
				return result;

			CrmWorkRecord workRecord = workRecordService.selectWorkRecordById(workId);
			return Result.SUCCESS(workRecord);
		} catch (Exception e) {
			return error("服务器出小差了~请稍后再试");
		}
	}

	/**
	 * 修改保存工作记录
	 */
	@ApiOperation(value = "修改保存", notes = "参数：CrmWorkRecord")
	// @RequiresPermissions("crm:work:edit")
	@Log(title = "工作记录", businessType = BusinessType.INSERT)
	@PostMapping("/edit")
	@ResponseBody
	public Result editSave(CrmWorkRecord workRecord) throws Exception {
		Result result = TokenUtil.verifyToken(workRecord.getKey());
		if (StringUtils.isNotNull(result))
			return result;
		return toResult(workRecordService.updateWorkRecord(workRecord));
	}

	/**
	 * 删除工作记录
	 */
	@ApiOperation(value = "删除对象", notes = "参数：ids，示例： id1,id2,id3，接口会转转为String[]类型")
	// @RequiresPermissions("crm:work:remove")
	@Log(title = "工作记录", businessType = BusinessType.DELETE)
	@PostMapping("/remove")
	@ResponseBody
	public Result remove(@RequestParam(value = "key") String token, @RequestParam(value = "ids") String ids) throws Exception {
		Result result = TokenUtil.verifyToken(token);
		if (StringUtils.isNotNull(result))
			return result;
		return toResult(workRecordService.deleteWorkRecordByIds(ids));
	}

	@ApiOperation(value = "工作统计", notes = "参数：userId, deptId, type, start, end")
	// @RequiresPermissions("crm:work:list")
	@Log(title = "工作统计", businessType = BusinessType.REQUEST)
	@PostMapping("/statistic")
	@ResponseBody
	public Result getWorkStatistics(@RequestParam(name = "key") String key,
	                                @RequestParam(name = "userId") Long userId,
	                                @RequestParam(name = "deptId", required = false) Long deptId,
	                                @RequestParam(name = "type") String type,
	                                @RequestParam(name = "start", required = false) Date startDate,
	                                @RequestParam(name = "end", required = false) Date endDate) throws Exception {
		// 先验证token
		Result result = TokenUtil.verifyToken(key);
		if (StringUtils.isNotNull(result))
			return result;
		if (StringUtils.isNull(userId)) {
			return error("用户信息为空");
		}
		// 季度参数（quarter:1,2,3,4）
		// if (StringUtils.isNotEmpty(type) && type.indexOf("quarter") >= 0) {
		// 	String quarter = type.substring(type.lastIndexOf(":") + 1);
		// 	String q[] = ConvertUtils.toStrArray(quarter);
		// 	startDate = DateUtils.beginOfQuarter(Integer.parseInt(q[0]));
		// 	endDate = DateUtils.endOfQuarter(Integer.parseInt(q[q.length - 1]));
		// }

		if (StringUtils.isNotEmpty(type) && type.equalsIgnoreCase("quarter")) {
			Date date = new Date();
			startDate = DateUtil.beginOfYear(date);
			endDate = date;
		}


		if (StringUtils.isNull(deptId)) {
			WorkTreeNode rootNode = workRecordService.personStatistics(userId, deptId, type, startDate, endDate);
			Map<String, WorkTreeNode> workTreeNodeMap = workRecordService.worklistForChart(userId, deptId, type, startDate, endDate);
			Map chartData = workRecordService.getChartData(workTreeNodeMap, type, startDate, endDate);

			Map data = new HashMap();
			data.put("chart", chartData);
			data.put("list", rootNode);
			data.put("depts", null);
			return Result.SUCCESS(data);
		} else {
			WorkTreeNode rootNode = workRecordService.statistics(null, deptId, type, startDate, endDate);
			Map<String, WorkTreeNode> workTreeNodeMap = workRecordService.worklistForChart(null, deptId, type, startDate, endDate);
			Map chartData = workRecordService.getChartData(workTreeNodeMap, type, startDate, endDate);
			List<SysDeptTree> depts = workRecordService.selectChildren(deptId);

			Map data = new HashMap();
			data.put("chart", chartData);
			data.put("list", rootNode);
			data.put("depts", depts);
			return Result.SUCCESS(data);
		}
	}



}